<template>
  <div
    class="player"
    :style="{
      top: size * position[0] + 'px',
      left: size * position[1] + 'px',
    }"
  >
    {{ dirs[direction] }}
  </div>
</template>

<script>
import { WALL, MOVE_1 } from "./constant";
import mixin from "./mixin";
export default {
  name: "Player",
  mixins: [mixin],
  props: {
    value: {
      type: Object,
      default: () => [],
    },
    size: {
      type: Number,
      default: () => 80,
    },
    map: {
      type: Array,
      default: () => [],
    },
    boxes: {
      type: Array,
      default: () => [],
    },
    target: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      position: [],
      direction: this.value.direction || 1,
      dirs: ["↑", "→", "↓", "←"],
    };
  },
  watch: {
    value() {
      this.position = this.value.position.slice() || [];
      this.direction = this.value.direction || 1;
    },
  },
  mounted() {
    window.addEventListener("keydown", this.onKeydown);
  },
  methods: {
    onKeydown(e) {
      let code = e.keyCode;
      let keys = [87, 68, 83, 65];
      let dir = keys.indexOf(code);
      this.direction = dir;
      this.move(dir);
    },
    move(dir) {
      // console.log("人前面有箱子", this.haveBox1(dir));
      // console.log("箱子前面有箱子", this.haveBox1(dir) && this.haveBox2(dir));
      // console.log("箱子前面有墙", this.haveBox1(dir) && this.haveWall2(dir));
      if (
        (!this.haveWall1(dir) && !this.haveBox1(dir)) ||
        (this.haveBox1(dir) && !this.haveBox2(dir) && !this.haveWall2(dir))
      ) {
        if (this.haveBox1(dir)) {
          let box = this.getFrontBox(dir);
          box.move(dir);
        }
        let m = MOVE_1[dir];
        let [x, y] = this.position;
        this.$set(this.position, 0, x + m[0]);
        this.$set(this.position, 1, y + m[1]);
        if (this.isSuccess()) {
          this.$emit("success");
        }
      }
    },
    getFrontBox(dir) {
      let direction = MOVE_1[dir];
      let zb = [
        this.position[0] + direction[0],
        this.position[1] + direction[1],
      ];
      return this.boxes.find((box) => {
        return box.position[0] === zb[0] && box.position[1] === zb[1];
      });
    },
    // 目标位置是否有箱子
    hasBox(target) {
      return !!this.boxes.find((box) => {
        return box.position[0] === target[0] && box.position[1] === target[1];
      });
    },
    // 判断游戏是否结束, 箱子全部到达目标点
    isSuccess() {
      return this.target.every((target) => {
        return this.hasBox(target);
      });
    },
  },
};
</script>

<style>
.player {
  position: absolute;
  width: 80px;
  height: 80px;
  background-color: #eeeeee;
  top: 320px;
  left: 320px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  z-index: 1;
}
</style>
